// Install an extra package that we need
net install labellist.pkg, from(http://fmwww.bc.edu/RePEc/bocode/l)


capture program drop balance_plot
program define balance_plot, rclass
    version 13
    syntax, ibvars(varlist) tvar(varlist) [cbvars(varlist)]
	local modcounter = 0
	matrix teffects = J(1,1,.)
	matrix tcis = J(2,1,.)
	foreach ibvar of varlist `ibvars' {
	  *levelsof `ibvar', local(levels)
	  labellist `ibvar'
	  local faclab = r(labels)
      local facval = r(values)
	  local levelcounter = 0
      foreach l of local facval {
	      local ++ levelcounter
	      local ++ modcounter
		  quietly gen __BPibvar = 1 if `ibvar' == `l'
		  quietly replace __BPibvar = 0 if __BPibvar == . & `ibvar' != .
	      get_b_ci, dvar(__BPibvar) tvar(`tvar')
		  *local lab `: word `levelcounter' of `faclab''
		  local lab `: word `levelcounter' of `faclab''
		  local varlab : subinstr local lab "$" "", all
          local varlab : subinstr local varlab " " "", all
          local varlab : subinstr local varlab "_i" "", all
		  matrix b = r(b)
		  matrix colnames b = "`varlab'"
		  matrix ci = r(ci)
		  matrix colnames ci = "`varlab'"
		  local check_first_model = teffects[1,1]
		  if `check_first_model' == . {
  	        matrix teffects =b
	        matrix tcis = ci
		  }
		  else {
  	        matrix teffects = teffects,b
	        matrix tcis = tcis,ci
		  }
		  quietly drop __BPibvar
	  }
	}
	if "`cbvars'" != "" {
		foreach var of varlist `cbvars' {
		  local ++ modcounter
		  get_b_ci, dvar(`var') tvar(`tvar')
		  matrix b = r(b)
		  local varlab: variable label `var'
		  matrix colnames b = "`varlab'"
		  matrix ci = r(ci)
		  matrix colnames ci = "`varlab'"
		  matrix teffects = teffects,b
		  matrix tcis = tcis,ci
		}
	}
	return matrix b = teffects
	return matrix ci = tcis
end


capture program drop get_b_ci
program define get_b_ci, rclass
    version 13
    syntax, dvar(varlist) tvar(varlist)
	quietly reg `dvar' `tvar'
	matrix b = e(b)
	matrix b = b[1,1]
    matrix V = e(V)
    local std_err = sqrt(V[1,1])
	local ci_upper = b[1,1] + 2*`std_err'
	local ci_lower = b[1,1] - 2*`std_err'
	matrix ci = (`ci_upper' \ `ci_lower')
	return matrix b = b
	return matrix ci = ci
end
